<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Redirect the user to the GitHub authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToGithub()
    {
        return Socialite::driver('github')
            ->with(['target' => request()->input('target')])
            ->scopes(['read:user', 'public_repo'])
            ->redirect();
    }

    /**
     * Obtain the user information from GitHub.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleGithubCallback(Request $request)
    {
        $githubUser = Socialite::driver('github')->user();
        $password = Str::random(10);
        $user = User::query()->updateOrCreate(
            ['email' => $githubUser->getEmail()],
            [
                'name' => $githubUser->getName(),
                'avatar'=> $githubUser->getAvatar(),
                'code' => Str::random(10),
                'email' => $githubUser->getEmail(),
                'password' => Hash::make($password),
                'oauth_provider' => 'github',
                'oauth_provider_id' => $githubUser->getId(),
                'oauth_provider_token' => $githubUser->token,
                'oauth_provider_expire_at' => now()->addSeconds($githubUser->expiresIn),
            ]
        );
        $user->save();
        Auth::login($user, true);
        $request->session()->regenerate();
        return redirect($this->redirectTo);
    }

    protected function validateLogin(Request $request)
    {
        $username = $request->get($this->username());
        $rule = is_numeric($username) ? 'regex:/^1[1-9]\\d{9}|\\d{6,9}$/' : 'email';
        $request->validate([
            $this->username() => ['required', 'string', $rule],
            'password' => 'required|string',
        ]);
    }

    public function username()
    {
        // to be email/mobile
        return 'username';
    }

    protected function credentials(Request $request)
    {
        $username = $request->get($this->username());
        $key = 'email';
        if (is_numeric($username)) {
            if (preg_match("/^1[1-9]\\d{9}$/", $username))
                $key = 'mobile';
            else
                $key = 'code';
        }
        return [
            $key => $request->get($this->username()),
            'password' => $request->get('password'),
            'revoked' => false
        ];
    }
}
